<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\panyuan\MyApplyCollection;
use App\model\agent\Agent;
use App\model\panyuan\Gonggao;
use App\model\panyuan\MyApply;
use App\model\panyuan\UserShenheSum;
use App\model\panyuan\WorkshopOverdue;
use App\model\UserWorkshop;
use App\model\UserWorkshopApply;
use App\model\Workshop;
use App\User;
use App\UserShenhe;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class UserController extends Controller
{
    public function agentUser(Request $request){
        $mobile=$request->mobile;
        $agent=Agent::whereMobile($mobile)->first();
      //  $agent=Agent::find(5);
        if (!$agent){
            return response()->json([
                'code'=>'error',
                'message'=>'请联系管理员添加名片'
            ]);
        }
       return response()->json([
            'code'=>'success',
            'message'=>'查询成功',
            'data'=>$agent
        ]);
    }
    /**
     * 我申请的房源
     * 我发布的房源
     * 我收藏的房源
     * 待更新的房源
     * @param Request $request
     */
    public function index(Request $request){
        $user=$request->user('api');
        $publish=Workshop::withoutGlobalScope('shenhe');
        if ($user->role_id==3){
           $publish=$publish ->where('user_id',$user->id);
        }
        $publish=$publish ->count();//发布的

        $apply=MyApply::where('user_id',$user->id)->where('type',MyApply::Updated_panyuan)->count();//申请的
        $collect=UserWorkshop::where('user_id',$user->id)->count();//收藏的
        $update=Workshop::where('user_id',$user->id)->count();//待更新的房源
        return response()->json(
            [
                'code'=>'success',
                'message'=>'获取成功',
                'data'=>compact('publish','apply','collect','update')
            ]
        );
    }

    /**
     * 排名
     */
    public function rank(Request $request){
        $user=$request->user('api');
        $time=$request->time;
        $start_time=Carbon::parse($time)->firstOfMonth()->format("Y-m-d H:i:s");
        $end_time=Carbon::parse($time)->addMonths(1)->format("Y-m-d H:i:s");
        $timeStr='WHERE created_at > ? And  created_at < ? ';
        $all_rank = \DB::select('select * from (SELECT (@i:=@i+1)"oid" ,workorder.* from (select COUNT(*) cou,user_id from workshop '.$timeStr.' GROUP BY user_id ORDER BY cou desc)workorder,(select @i:=0)t
            ) abc where user_id=?', [$start_time,$end_time, $user->id]);

         $user_total=User::count();
        $dian_rank = \DB::select('select * from (SELECT (@i:=@i+1)"oid" ,workorder.* from (SELECT * from (select COUNT(*) cou,user_id from workshop '.$timeStr.'  GROUP BY user_id ORDER BY cou desc)workorder where user_id in(select user_id from user_department_id where department_id=(select department_id from user_department_id where user_id='.$user->id.') )
            )workorder,(select @i:=0)t) abc where user_id=?', [$start_time,$end_time,$user->id]);

        $qu_rank = \DB::select('select * from (SELECT (@i:=@i+1)"oid" ,workorder.* from (SELECT * from (select COUNT(*) cou,user_id from workshop '.$timeStr.' GROUP BY user_id ORDER BY cou desc)workorder where user_id in(select user_id from user_department_id where department_id=(select department_id from user_department_id where user_id='.$user->id.') )
            )workorder,(select @i:=0)t) abc where user_id=?', [$start_time,$end_time,$user->id]);
        $ranking = \DB::select('select pai.*,u.name FROM(select * from (SELECT (@i:=@i+1)"oid" ,workorder.* from (select COUNT(*) cou,user_id from workshop '.$timeStr.' GROUP BY user_id ORDER BY cou desc)workorder,(select @i:=0)t) abc )pai LEFT JOIN  users u  on u.id=pai.user_id LIMIT 10', [$start_time,$end_time]);
        //查询比自己少的
       // dd(compact('all_rank','dian_rank','qu_rank','ranking','user_total'));

        return response()->json([
            'code'=>'success',
            'data'=>[
                'all_rank'=>empty($all_rank) ? [['oid'=>0 ,'user_id'=>0,'cou'=>0]] : $all_rank,
              'dian_rank'=>empty($dian_rank) ? [['oid'=>0 ,'user_id'=>0,'cou'=>0]] : $dian_rank,
                'qu_rank'=>empty($qu_rank) ? [['oid'=>0 ,'user_id'=>0,'cou'=>0]] : $qu_rank,
                'ranking'=>$ranking,
                'user_total'=>$user_total]
        ]);

    }
    /**
     * 用户数据
     */
    public function data(Request $request){
        $user=$request->user('api');
        $workshop=Workshop::query();
        if($user->role_id==3){
           //盘源总数

            $all=Workshop::where('user_id',$user->id)->count();
            $Lastmonth=Workshop::where('created_at','>',Carbon::now()->subMonth()->firstOfMonth())
                ->where('user_id',$user->id)
                ->where('created_at','<',Carbon::now()->firstOfMonth())
                ->count();
            $month=Workshop::where('created_at','>',Carbon::now()->firstOfMonth())
                ->where('user_id',$user->id)
                ->count();
            $chengjiao=Workshop::whereIn('status',[2,3,4,5])->where('user_id',$user->id)->count();
            $area=Workshop::where('user_id',$user->id)->sum('area');
            $yesterday=Workshop::where('created_at','>',Carbon::yesterday())
                ->where('user_id',$user->id)
                ->where('created_at','<',Carbon::today())
                ->count();
            $weekday=Workshop::where('created_at','>',Carbon::now()->startOfWeek())
                ->where('user_id',$user->id)
                ->count();
        }else{
            $all=Workshop::count();
            $Lastmonth=Workshop::where('created_at','>',Carbon::now()->subMonth()->firstOfMonth())
                ->where('created_at','<',Carbon::now()->firstOfMonth())
                ->count();

            $chengjiao=0;
            $month=Workshop::where('created_at','>',Carbon::now()->firstOfMonth())
                ->count();
            $area=Workshop::sum('area');
            $yesterday=Workshop::where('created_at','>',Carbon::yesterday())
                ->where('created_at','<',Carbon::today())
                ->count();
            $weekday=Workshop::where('created_at','>',Carbon::now()->startOfWeek())->count();
        }

        return response()->json([
            'code'=>'success',
            'data'=>compact('all','Lastmonth','month','area','yesterday','weekday','chengjiao')
        ]);
    }
    public function applyList(Request $request){
        $status=$request->status;
        $search_key=$request->search_key;
        $myApply=MyApply::with(['workshop'=>function($query){
            $query-> withoutGlobalScope('shenhe')->with(['industry','tags']);
        }])->where('type',MyApply::Updated_panyuan)
           ->where('user_id',$request->user('api')->id)
        ;
        if ($status){
            $myApply=$myApply->where('status',$status);
        }else{
            $myApply=$myApply->where('status',MyApply::SHENHE);
        }
        if ($search_key){
            $myApply=$myApply->whereHas('workshop',function($query)use($search_key){
                $query->withoutGlobalScope('shenhe')->where('title','like','%'.$search_key."%")
                    ->orWhere('owner','like','%'.$search_key."%");
            });
        }

        $myApply=$myApply->orderBy('updated_at','desc')->paginate(20);

        return new MyApplyCollection($myApply);
    }
    public function applyShenqing(Request $request){
        $type=$request->get('type',0);
        $search_key=$request->search_key;
        $myApply=MyApply::with(['workshop'=>function($query){
            $query-> withoutGlobalScope('shenhe')->with(['industry','tags']);
        }])->where('type','=',$type)  ->where('user_id',$request->user('api')->id) ;

        $myApply=$myApply->orderBy('updated_at','desc')->paginate(20);

        return new MyApplyCollection($myApply);
    }

    /**
     * 提醒消息条数
     */
    public function userNotify(Request $request){
        $user=$request->user('api');
        //审批
        if ($user->role_id!=3){
            $shenhe=UserShenhe::where('role_id',$user->role_id)
                ->where('status',UserShenhe::STATUS_SHENHE)
                ->count();
           $overdue= WorkshopOverdue::where('user_id',$user->id)->where('is_updated',WorkshopOverdue::NO_UPDATED)->count();

        }else{
            /*$shenhe=MyApply::where('user_id',$user->id)
                ->whereIn('status',[MyApply::SHENHE,MyApply::SHENHE_REFUSE])
                ->count();*/
            $shenhe=UserShenheSum::where('user_id',$request->user('api')->id)->first()->num ?? 0;
            $overdue= WorkshopOverdue::where('user_id',$user->id)->where('is_updated',WorkshopOverdue::NO_UPDATED)->count();
        }
        $update=Workshop::where('user_id',$user->id)->where('updated_at','<',Carbon::now()->addDays(-10))->count();
        $notice=Gonggao::count();
        return response()->json([
            'code'=>'success',
            'data'=>compact(
                'shenhe','overdue','update','notice'
            )
        ]);

    }
}
